package com.nightwalkbuddy.service;

import com.nightwalkbuddy.dto.MapPair;
import com.nightwalkbuddy.dto.MapPath;

/**
 * FUTURE IMPLEMENTATION: create reverse route for round trip and save specific
 * point where the user goes astray or when panic button is switched on
 * 
 * @author - htisabel
 */
public class PathServiceLive implements IPathService {

	final static private double LENGTH_TOLERANCE = 1;
	final static private double DEVI_TOLERANCE = 1;
	private MapPath aMapPath = new MapPath();
	private double finalLength = 0, finalDevi = 0;
	private double startLat = 0, startLong = 0;
	private double betweenLat = 0, betweenLong = 0;
	private double finLat = 0, finLong = 0;
	private double lengthToFinish = 0, lengthFromStart = 0;

	@Override
	public void pointToPath(double latitude, double longitude) throws Exception {
		aMapPath.setMapPointPair(latitude, longitude);
		aMapPath.setaMap();
		betweenLat = latitude;
		betweenLong = longitude;
	}

	@Override
	public void setDestination(MapPair<Double, Double> startGPS,
			MapPair<Double, Double> finishGPS) {
		startLat = startGPS.getFirst();
		startLong = startGPS.getSecond();
		finLat = finishGPS.getFirst();
		finLong = finishGPS.getSecond();
		finalLength = Math.sqrt(Math.pow((finLat - startLat), 2)
				+ Math.pow((finLong - startLong), 2))
				+ LENGTH_TOLERANCE;
		finalDevi = Math.atan2(finLong - startLong, finLat - startLat);
	}

	@Override
	public String printPathPoints() throws Exception {
		String aPath = "";
		aPath = lengthFromStart + " toFinish: " + lengthToFinish + " devi: "
				+ aMapPath.getDevi() + " finalDevi: " + finalDevi;
		return aPath;
	}

	@Override
	public boolean isOnPath() {
		boolean onPath = false;
		double deviNow = aMapPath.getDevi();
		double deviDiff = Math.pow((deviNow - finalDevi), 2);
		lengthToFinish = Math.sqrt(Math.pow((finLat - betweenLat), 2)
				+ Math.pow((finLong - betweenLong), 2));
		lengthFromStart = Math.sqrt(Math.pow((betweenLat - startLat), 2)
				+ Math.pow((betweenLong - startLong), 2));
		if (lengthToFinish + lengthFromStart <= finalLength) {
			if (deviDiff <= DEVI_TOLERANCE) {
				onPath = true;
			}
		}
		return onPath;
	}

	@Override
	public String getCompletePath() throws Exception {
		return aMapPath.getMapPrint();
	}

	@Override
	public String getPathInProgress() {
		return aMapPath.printMapPath();
	};

}
